/*
  Copyright 2012 Sergey Ostanin

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

package ru.irenproject;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import ru.irenproject.store.AbstractThing;
import ru.irenproject.store.Event;
import ru.irenproject.store.Stash;

import com.google.common.collect.Iterators;
import com.google.common.collect.UnmodifiableIterator;
import com.google.protobuf.ByteString;

public final class ProfileList extends AbstractThing implements Iterable<Profile> {
  public enum ChangeEvent implements Event { INSTANCE }

  public static final class AddEvent implements Event {
    private final Profile fProfile;

    private AddEvent(Profile profile) {
      fProfile = profile;
    }

    public Profile profile() {
      return fProfile;
    }
  }

  @Stash private TestProtos.ProfileList.Builder $;

  @Inject ProfileList() {}

  public void add(Profile profile) {
    $.addProfile(profile.id());
    post(new AddEvent(profile));
    post(ChangeEvent.INSTANCE);
  }

  public List<Profile> list() {
    return store().getBatch($.getProfileList(), Profile.class);
  }

  @Override public UnmodifiableIterator<Profile> iterator() {
    return Iterators.unmodifiableIterator(list().iterator());
  }

  public Profile get(int index) {
    checkIndex(index);
    return store().get($.getProfile(index), Profile.class);
  }

  public int count() {
    return $.getProfileCount();
  }

  public boolean isEmpty() {
    return count() == 0;
  }

  public void delete(int index) {
    checkIndex(index);

    List<ByteString> ids = new ArrayList<>($.getProfileList());
    ids.remove(index);
    $.clearProfile().addAllProfile(ids);

    post(ChangeEvent.INSTANCE);
  }

  public boolean contains(Profile profile) {
    return $.getProfileList().contains(profile.id());
  }

  public int indexOf(Profile profile) {
    return $.getProfileList().indexOf(profile.id());
  }

  public void move(int index, boolean forward) {
    checkIndex(index);
    int newIndex = index + (forward ? 1 : -1);
    checkIndex(newIndex);

    ByteString temp = $.getProfile(index);
    $.setProfile(index, $.getProfile(newIndex));
    $.setProfile(newIndex, temp);

    post(ChangeEvent.INSTANCE);
  }

  private void checkIndex(int index) {
    TestCheck.input(index >= 0);
    TestCheck.input(index < count());
  }
}
